package com.yupi.yuapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.yuapiclientsdk.model.User;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import com.yupi.yuapiclientsdk.utils.SignUtils;


@Slf4j
public class JairInterfaceClient {

    private String accessKey;
    private String secretKey;
    private String BASE_URL = "http://localhost:8090/user";

    public JairInterfaceClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        log.info("Get方法");
        HashMap<String, Object> params= new HashMap<>();
        params.put("name", name);
        return HttpUtil.get(BASE_URL+"/get",params);
    }


    // 使用POST方法从服务器获取名称信息
    public String getNameByPost(String name) {
        log.info("Post方法");
        // 可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        // 使用HttpUtil工具发起POST请求，并获取服务器返回的结果
        return HttpUtil.post(BASE_URL+"/post", paramMap);
    }

    public String getUserNameByPost(User user) {
        log.info("Post方法");
        String json = JSONUtil.toJsonStr(user);

        // Base64编码处理中文
        String encodedBody = Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8));

        // 添加调试日志
        log.info("客户端发送 - body: {}", json);
        log.info("客户端编码后 - body: {}", encodedBody);
        log.info("请求URL: {}", BASE_URL+"/user");

        try {
            String result2 = HttpRequest.post(BASE_URL)
                    .body(json)  // 请求体：原始JSON
                    .addHeaders(getHeaderMap(encodedBody))  // 请求头：Base64编码的JSON
                    .execute().body();
            log.info("HTTP响应结果: [{}]", result2);
            return result2;
        } catch (Exception e) {
            log.error("HTTP请求失败: {}", e.getMessage(), e);
            return null;
        }
    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body); // 使用Base64编码的body
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", SignUtils.genSign(body, secretKey));
        return hashMap;
    }
}

